package com.kang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kang.dto.ParkDto;
import com.kang.entity.*;
import com.kang.mapper.*;
import com.kang.service.ParkService;
import com.kang.util.ThreadLocalUtil;
import com.kang.vo.ParamInfo;
import com.kang.vo.ParkVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ParkServiceImpl extends ServiceImpl<ParkMapper, Park> implements ParkService {


    @Autowired
    private ParkMapper parkMapper;

    @Autowired
    private ParkUserMapper parkUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EssayMapper essayMapper;

    @Autowired
    private ParkAppMapper parkAppMapper;

    @Override
    public Integer insertPark(Park park) {
        //添加社区
        park.setCreateTime(new Date());
        park.setUpdateTime(new Date());
        park.setStatus(1);
        park.setCreateBy(ThreadLocalUtil.getCurrentUser().getName());
        park.setCreateUserId(ThreadLocalUtil.getCurrentUser().getId());
        parkMapper.insert(park);
        //添加关联表
        ParkUser parkUser = new ParkUser();
        parkUser.setParkId(park.getId());
        parkUser.setUserId(ThreadLocalUtil.getCurrentUser().getId());
        parkUser.setCreateTime(new Date());
        parkUser.setUpdateTime(new Date());
        parkUserMapper.insert(parkUser);
        return 1;
    }

    @Override
    public Integer deletePark(Integer parkId) {
        //删除社区
        parkMapper.deleteById(parkId);
        //删除关联用户
        QueryWrapper<ParkUser> wrapper = new QueryWrapper<>();
        wrapper.eq("park_id",parkId);
        parkUserMapper.delete(wrapper);
        //删除当前社区审核的信息
        QueryWrapper<ParkApp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("park_id",parkId);
        parkAppMapper.delete(queryWrapper);
        return 1;
    }

    @Override
    public Integer updatePark(Park park) {
        UpdateWrapper<Park> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",park.getId()).set("park_name",park.getParkName()).set("park_des",park.getParkName())
                .set("park_url",park.getParkUrl()).set("update_time",new Date());
        parkMapper.update(null,wrapper);
        return 1;
    }

    @Override
    public ParkDto getParkById(Integer id) {
        //查询园区信息
        Park park = parkMapper.selectById(id);
        //查询园区用户信息
        QueryWrapper<ParkUser> wrapper = new QueryWrapper<>();
        wrapper.eq("park_id",id);
        List<ParkUser> parkUsers = parkUserMapper.selectList(wrapper);
        ParkDto parkDto = new ParkDto();
        parkDto.setPark(park);
        parkDto.setParkUsers(parkUsers);
        return parkDto;
    }

    @Override
    public Page<Park> getParkPage(ParamInfo paramInfo) {
        Page<Park> page = new Page<>(paramInfo.getPageNum(), paramInfo.getPageSize());
        QueryWrapper<Park> wrapper = new QueryWrapper<>();
        wrapper.eq("status",2);
        wrapper.like(paramInfo.getParkName() != null,"park_name",paramInfo.getParkName());
        wrapper.between(paramInfo.getStartTime() != null,"create_time",paramInfo.getStartTime(),paramInfo.getEndTime());
        wrapper.last("order by create_time desc");
        Page<Park> parkPage = parkMapper.selectPage(page, wrapper);
        if ("2".equals(String.valueOf(paramInfo.getStatus()))) {
            return parkPage;
        }
        //查询用户所在的社区
        Integer userId = ThreadLocalUtil.getCurrentUser().getId();
        List<Integer> parkIdList = parkUserMapper.selectList(new QueryWrapper<ParkUser>().eq("user_id", userId)).stream().map(ParkUser::getParkId).collect(Collectors.toList());
        parkPage.getRecords().forEach(v -> {
            if (v.getParkDes().length() > 50) {
                v.setParkDes(v.getParkDes().substring(0,50) + "...");
            }
            for (Integer integer : parkIdList) {
                if (v.getId().equals(integer)) {
                    v.setType(2);
                    break;
                }
            }
        });
        return parkPage;
    }

    @Override
    public List<Park> getParkList() {
        Integer userId = ThreadLocalUtil.getCurrentUser().getId();
        //获取园区id
        QueryWrapper<ParkUser> wrapper = new QueryWrapper<>();
        wrapper.eq("userId", userId);
        List<Integer> parkIdList = parkUserMapper.selectList(wrapper).stream().map(ParkUser::getParkId).collect(Collectors.toList());
        //获取园区
        List<Park> resultList = new ArrayList<>();
        if (parkIdList.size() != 0) {
            QueryWrapper<Park> wrapper1 = new QueryWrapper<>();
            wrapper1.in("id",parkIdList);
            wrapper1.eq("status",2);
            resultList = parkMapper.selectList(wrapper1);
        }
        return resultList;
    }

    @Override
    public Page<Park> getParkListByPerson(ParamInfo vo) {
        Page<Park> page = new Page<>(vo.getPageNum(), vo.getPageSize());
        Integer userId = ThreadLocalUtil.getCurrentUser().getId();
        QueryWrapper<ParkUser> wrapper = new QueryWrapper<>();
        wrapper.in("user_id",userId);
        List<Integer> collect = parkUserMapper.selectList(wrapper).stream().map(ParkUser::getParkId).collect(Collectors.toList());
        QueryWrapper<Park> wrapper2 = new QueryWrapper<>();
        wrapper2.in("id",collect).eq("status",2);
        Page<Park> selectPage = parkMapper.selectPage(page, wrapper2);
        if (vo.getPersonPark() == null) {
            return selectPage;
        } else {
            QueryWrapper<Park> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("create_user_id",userId);
            queryWrapper.eq("status",2);
            Page<Park> parkPage = parkMapper.selectPage(page, queryWrapper);
            if (vo.getPersonPark() == 1) {
                return parkPage;
            } else {
                //加入社区的分页
//                QueryWrapper<Park> wrapper1 = new QueryWrapper<>();
//                wrapper1.in("id",collect);
                List<Park> parks = parkMapper.selectList(wrapper2);
                List<Park> parks1 = parkMapper.selectList(queryWrapper);
                parks.removeAll(parks1);
                //加入社区的所以id
                Page<Park> parkPage1 = new Page<>();
                if (parks.size() != 0) {
                    List<Integer> integerList = parks.stream().map(Park::getId).collect(Collectors.toList());
                    parkPage1 = parkMapper.selectPage(page, new QueryWrapper<Park>().in("id", integerList));
                    return parkPage1;
                }
                return parkPage1;
            }
        }
    }

    @Override
    public Integer appJoinPark(ParkVo vo) {
        ParkUser parkUser = new ParkUser();
        parkUser.setParkId(vo.getParkId());
        parkUser.setUserId(ThreadLocalUtil.getCurrentUser().getId());
        parkUser.setCreateTime(new Date());
        parkUser.setUpdateTime(new Date());
        return parkUserMapper.insert(parkUser);
    }

    @Override
    public Integer outPark(ParkVo vo) {
        QueryWrapper<ParkUser> wrapper = new QueryWrapper<>();
        wrapper.eq("park_id",vo.getParkId());
        wrapper.eq("user_id",ThreadLocalUtil.getCurrentUser().getId());
        return parkUserMapper.delete(wrapper);
    }

    @Override
    public List<SysUser> getUserByPark(ParkVo vo) {
        QueryWrapper<ParkUser> wrapper = new QueryWrapper<>();
        wrapper.eq("park_id",vo.getParkId());
        List<Integer> collect = parkUserMapper.selectList(wrapper).stream().map(ParkUser::getUserId).collect(Collectors.toList());
        QueryWrapper<SysUser> wrapper1 = new QueryWrapper<>();
        wrapper.in("id",collect);
        wrapper.last("order by create_time asc");
        return userMapper.selectList(wrapper1);
    }

    @Override
    public Integer kickOutPark(ParkVo vo) {
        QueryWrapper<ParkUser> wrapper = new QueryWrapper<>();
        wrapper.eq("park_id",vo.getParkId());
        wrapper.eq("user_id",vo.getUserId());
        return parkUserMapper.delete(wrapper);
    }

    @Override
    public Page<Essay> getParkEssay(ParkVo vo) {
        Page<Essay> page = new Page<>(vo.getPageNum(), vo.getPageSize());
        QueryWrapper<Essay> wrapper = new QueryWrapper<>();
        wrapper.ne("park_id",0);
        wrapper.last("order by create_time desc");
        return essayMapper.selectPage(page, wrapper);
    }

    @Override
    public Integer appPark(Integer parkId) throws Exception {
        Integer userId = ThreadLocalUtil.getCurrentUser().getId();
        Integer count = parkAppMapper.selectCount(new QueryWrapper<ParkApp>().eq("user_id", userId).eq("park_id", parkId).eq("status", 1));
        if (count != 0) {
            throw new Exception("当前用户已申请加入社区，请耐心等待审核！");
        }
        ParkApp parkApp = new ParkApp();
        parkApp.setCreateTime(new Date());
        parkApp.setStatus(1);
        parkApp.setUpdateTime(new Date());
        parkApp.setParkId(parkId);
        parkApp.setUserId(userId);
        return parkAppMapper.insert(parkApp);
    }

    @Override
    public Integer disposeApp(ParkVo vo) {
        UpdateWrapper<ParkApp> wrapper = new UpdateWrapper<>();
        wrapper.eq("user_id",vo.getUserId()).eq("park_id",vo.getParkId());
        //前端传的不是2就是3与数据库固定
        wrapper.set("status",vo.getStatus());
        if (vo.getStatus() == 2) {
            ParkUser parkUser = new ParkUser();
            parkUser.setParkId(vo.getParkId());
            parkUser.setUserId(vo.getUserId());
            parkUser.setCreateTime(new Date());
            parkUser.setUpdateTime(new Date());
            parkUserMapper.insert(parkUser);
        }
        return parkAppMapper.update(null,wrapper);
    }

    @Override
    public List<ParkApp> disposeAppList(Integer parkId) {
//        Integer userId = ThreadLocalUtil.getCurrentUser().getId();
//        //获取当前用户所建立的社区
//        List<Park> parkList = parkMapper.selectList(new QueryWrapper<Park>().eq("create_user_id", userId));
//        //获取社区的id
//        List<Integer> parkIdList = parkList.stream().map(Park::getId).collect(Collectors.toList());
//        if (parkIdList.size() != 0) {
        Park park = parkMapper.selectById(parkId);
        QueryWrapper<ParkApp> wrapper = new QueryWrapper<>();
        wrapper.eq("park_id",parkId).eq("status",1);
        List<ParkApp> parkApps = parkAppMapper.selectList(wrapper);
        //获取当前申请的用户id
        List<Integer> userIdList = parkApps.stream().map(ParkApp::getUserId).collect(Collectors.toList());
        //查询用户信息
        List<SysUser> userList = new ArrayList<>();
        if (userIdList.size() != 0) {
            userList = userMapper.selectList(new QueryWrapper<SysUser>().in("id",userIdList));
        }
        List<SysUser> finalUserList = userList;
        parkApps.forEach(v -> {
            for (SysUser user : finalUserList) {
                if (v.getUserId().equals(user.getId())) {
                    v.setUsername(user.getUsername());
                    v.setHeadUrl(user.getHeadUrl());
                }
            }
            //设置社区名称
            v.setParkName(park.getParkName());
        });
        return parkApps;
    }

    @Override
    public Page<Park> getParkAudit(ParkVo parkVo) {
        Page<Park> page = new Page<>(parkVo.getPageNum(), parkVo.getPageSize());
        Integer userId = ThreadLocalUtil.getCurrentUser().getId();
        QueryWrapper<Park> wrapper = new QueryWrapper<>();
        wrapper.eq("create_user_id",userId).eq("status",1);
        return parkMapper.selectPage(page,wrapper);
    }

    @Override
    public List<SysUser> getParkUser(Integer parkId) {
        List<Integer> userIdList = new ArrayList<>();
        //获取创建人
        Park park = parkMapper.selectById(parkId);
        userIdList.add(park.getCreateUserId());
        //获取所以成员
        List<ParkUser> parkUsers = parkUserMapper.selectList(new QueryWrapper<ParkUser>().eq("park_id", parkId).ne("user_id", park.getCreateUserId()));
        userIdList.addAll(parkUsers.stream().map(ParkUser::getUserId).collect(Collectors.toList()));
        //找的用户头像和名称
        return userMapper.selectList(new QueryWrapper<SysUser>().in("id", userIdList));
    }
}
